#!/bin/bash

# 纸牌接龙 Qt 原生 OpenGL 示例 项目编译脚本
# 适用于 macOS

set -e  # 遇到错误立即退出

echo "=========================================="
echo "Solitaire Qt 原生 OpenGL 编译脚本"
echo "=========================================="

# 允许用户通过环境变量覆盖 Qt 路径
if [ -n "$QT6_PATH" ]; then
  echo "使用用户提供的 QT6_PATH: $QT6_PATH"
fi

# 检测Qt6路径（支持常见 Homebrew 路径与用户目录安装）
CANDIDATE_PATHS=(
  "$QT6_PATH"
  "$CMAKE_PREFIX_PATH"
  "$HOME/qt6"
  "~/qt6"
  "$HOME/Qt/6.*/macos"
  "/opt/homebrew/opt/qt@6"
  "/usr/local/opt/qt@6"
  "/opt/homebrew/Cellar/qt@6/*"
  "/usr/local/Cellar/qt@6/*"
)

RESOLVED_QT_PATH=""
for path in "${CANDIDATE_PATHS[@]}"; do
  # 展开可能的通配符
  for p in $(echo $path); do
    if [ -d "$p" ]; then
      RESOLVED_QT_PATH="$p"
      echo "✓ 找到Qt6: $RESOLVED_QT_PATH"
      break 2
    fi
  done
done

if [ -z "$RESOLVED_QT_PATH" ]; then
  echo "✗ 错误: 找不到Qt6安装路径"
  echo "请先安装Qt6: brew install qt@6 或将Qt安装到 ~/qt6"
  echo "也可设置环境变量 QT6_PATH 或 CMAKE_PREFIX_PATH 指向Qt6安装目录"
  exit 1
fi

# 设置环境变量
export PATH="$RESOLVED_QT_PATH/bin:$PATH"
export CMAKE_PREFIX_PATH="$RESOLVED_QT_PATH"

echo "使用的 CMAKE_PREFIX_PATH: $CMAKE_PREFIX_PATH"

# 创建build目录
BUILD_DIR="build"
if [ -d "$BUILD_DIR" ]; then
  echo "清理旧的build目录..."
  rm -rf "$BUILD_DIR"
fi

mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"

echo ""
echo "=========================================="
echo "配置CMake..."
echo "=========================================="

# 配置CMake（在macOS上使用OpenGL）
cmake .. \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_PREFIX_PATH="$CMAKE_PREFIX_PATH" \
  -DCMAKE_OSX_ARCHITECTURES=arm64

echo ""
echo "=========================================="
echo "开始编译..."
echo "=========================================="

# 编译（使用所有CPU核心）
cmake --build . -j$(sysctl -n hw.ncpu)

echo ""
echo "=========================================="
echo "编译完成！"
echo "=========================================="
echo ""
echo "运行程序："
echo "  ./QtOpenGLDemo.app/Contents/MacOS/QtOpenGLDemo"
echo ""
echo "或者："
echo "  open ./QtOpenGLDemo.app"
echo ""